package com.gmadmin.utils;


import cn.hutool.json.JSONUtil;
import com.gmadmin.common.ApiResponse;
import com.gmadmin.common.IStatus;
import com.gmadmin.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/1/25 15:17
 */
public class ResponseUtil {

    protected static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    private ResponseUtil() {
    }

    /**
     * 往 response 写出 json
     *
     * @param response 响应
     * @param status   状态
     * @param data     返回数据
     */
    public static void renderJson(HttpServletResponse response, IStatus status, Object data) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(500);
            logger.info("{}: {}", status.value(), status.getReasonPhrase());
            response.getWriter().write(Objects.requireNonNull(JSONUtil.toJsonStr(new ApiResponse<>().ofStatus(status, data))));
        } catch (IOException e) {
            logger.error("Response写出JSON异常，", e);
        }
    }

    /**
     * 往 response 写出 json
     * BaseException exception
     *
     * @param response 响应
     */
    public static void renderJson(HttpServletResponse response, BaseException exception) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            // response返回服务器状态只能是系统自带
            response.setStatus(500);

            response.getWriter().write(Objects.requireNonNull(JSONUtil.toJsonStr(new ApiResponse<>().ofException(exception))));
        } catch (IOException e) {
            logger.error("Response写出JSON异常，", e);
        }
    }
}
